<template>
  <div class="zero-code-list">
    <a-spin :spinning="grid.loading">
      <vxe-grid v-if="!grid.loading" v-bind="grid" :ref="record.key">
        <template #toolbar_buttons>
          <a-button
            type="link"
            icon="plus"
            @click="add"
            v-if="record.options.canAdd"
          >
            新增
          </a-button>
          <a-button type="link" icon="edit" v-if="record.options.canEdit">
            编辑</a-button
          >
          <a-popconfirm
            v-if="record.options.canDelete"
            title="确定删除数据?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="delAll"
          >
            <a-button type="link" v-if="record.options.canDelete">
              <a-icon type="delete" style="color: #ff4d4f"></a-icon>
              <span class="text-red"> 删除 </span>
            </a-button>
          </a-popconfirm>

          <a-button type="link" icon="import" v-if="record.options.canAdd">
            导入</a-button
          >
          <a-dropdown v-if="record.options.canReport">
            <a-menu slot="overlay">
              <a-menu-item key="1">
                <a-icon type="file-excel" />导出记录(excel)
              </a-menu-item>
              <a-menu-item key="2">
                <a-icon type="file-zip" />导出附件
              </a-menu-item>
              <a-menu-item key="3">
                <a-icon type="file-pdf" />导出PDF
              </a-menu-item>
            </a-menu>
            <a-button type="link" icon="download">
              导出
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </template>
        <template #toolbar_tools> </template>
        <template #loading>
          <a-spin></a-spin>
        </template>
        <template #empty>
          <eip-empty />
        </template>
        <template #checkboxHeader="{ checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleAllCheckboxRow()">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>
        <template #checkbox="{ row, checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleCheckboxRow(row)">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>

        <template #operate="{ row }">
          <a-dropdown>
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1">
                <a-tooltip title="复制" v-if="record.options.canAdd">
                  <a-icon
                    @click="copy(row)"
                    type="copy"
                    class="eip-cursor-pointer"
                  ></a-icon>
                </a-tooltip>
              </a-menu-item>
              <a-menu-item key="2">
                <a-tooltip title="" v-if="record.options.canEdit">
                  <a-icon type="edit" class="eip-cursor-pointer"></a-icon
                  >编辑</a-tooltip
                >
              </a-menu-item>
              <a-menu-item key="3">
                <a-popconfirm
                  v-if="record.options.canDelete"
                  title="确定删除数据?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="remove(row)"
                >
                  <a-tooltip title="删除">
                    <a-icon
                      type="delete"
                      style="color: red"
                      class="eip-cursor-pointer"
                    ></a-icon>
                  </a-tooltip>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
            <a-icon type="more" :rotate="90" />
          </a-dropdown>
        </template>
        <!-- 序号 -->
        <template #seq="">
          <span>序号</span>
        </template>
        <template #edit="{ row, column }">
          <div
            v-for="(item, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + item.type"
              :column="column"
              :row="row"
              :item="item"
              :isEdit="true"
              @change="updateStatus({ row, column })"
            ></component>
          </div>
        </template>
        <!-- 格式化内容 -->
        <template #default="{ row, column }">
          <div
            v-for="(item, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + item.type"
              :column="column"
              :row="row"
              :item="item"
              :isEdit="false"
            ></component>
          </div>
        </template>
      </vxe-grid>
    </a-spin>
  </div>
</template>
<script>
import { newGuid } from "@/utils/util";
import gridInput from "./grid/input.vue";
import gridTextarea from "./grid/textarea.vue";
import gridSwitch from "./grid/switch.vue";
import gridNumber from "./grid/number.vue";
import gridRadio from "./grid/radio.vue";
import gridSelect from "./grid/select.vue";
import gridCheckbox from "./grid/checkbox.vue";
import gridSys from "./grid/sys.vue";
import gridSerialNo from "./grid/serialNo.vue";
import {
  findCorrelationRows,
  findCorrelationDefault,
  findById,
} from "@/services/system/zerocode/run/edit";
export default {
  components: {
    einput: gridInput,
    etextarea: gridTextarea,
    eswitch: gridSwitch,
    enumber: gridNumber,
    eeradio: gridRadio,
    eeselect: gridSelect,
    eecheckbox: gridCheckbox,
    esys: gridSys,
    eserialNo: gridSerialNo,
  },
  data() {
    return {
      componentName: "", //组件名称
      grid: {
        loading: true,
      },
      columns: [],
    };
  },
  props: ["record", "value", "formValue", "parentDisabled", "worksheet"],
  watch: {
    "record.options.columns": {
      handler: function (newVal, oldVal) {
        if (newVal.length != oldVal.length) {
          this.initColumn();
        }
      },
      deep: true,
    },
  },
  created() {
    this.initGridOption();
    this.initGridData();
  },
  methods: {
    /**
     * 更改值状态
     */
    updateStatus(row, column) {
      this.$refs[this.record.key].updateStatus({ row, column });
      this.handleInput();
    },

    /**
     * 改变事件
     */
    handleInput() {
      this.$emit("change", this.grid.data);
    },

    /**
     *
     */
    getOptions(field) {
      return this.$utils.find(
        this.record.options.columns,
        (f) => f.key == field
      );
    },
    /**
     *初始化列表配置项
     */
    initGridOption() {
      this.grid = {
        id: "correlation-grid",
        editConfig: {
          trigger: "click",
          mode: "cell",
        },
        loading: true,
        seqConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        customConfig: {
          mode: "popup",
        },
        sortConfig: {
          trigger: "cell",
          defaultSort: {},
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: [],
        data: [],
        extend: {
          id: null,
        },
      };
      //判断是否
      this.initColumn();
    },

    /**
     * 初始化列
     */
    initColumn() {
      let that = this;
      this.grid.columns = [];
      this.grid.columns.push({
        type: "checkbox",
        width: 50,
        align: "center",
        fixed: "left",
        resizable: false,
        slots: {
          checkbox: "checkbox",
          header: "checkboxHeader",
        },
      });
      this.grid.columns.push({
        title: "操作",
        width: 50,
        align: "center",
        fixed: "left",
        slots: {
          default: "operate",
        },
      });

      //是否显示序号
      this.grid.columns.push({
        type: "seq",
        width: 50,
        fixed: "left",
        resizable: false,
        slots: {
          header: "seq",
        },
      });

      //获取
      findById(this.record.options.zeroCodeId).then(function (result) {
        that.columns = JSON.parse(result.data.columnJson);
        that.columns
          .filter((f) => that.record.options.columns.includes(f.key))
          .forEach((element) => {
            let column = {
              field: element.key,
              title: element.label,
              width: element.width,
              sortable: true,
              slots: {
                edit: "edit",
              },
              editRender: {
                enabled: that.record.options.canEdit,
              },
              showOverflow: "ellipsis",
              filterRender: {
                name: "MLFilterRender",
              },
              filters: [
                {
                  data: {
                    type: "input",
                    key: null,
                    op: "cn",
                    write: null,
                    options: [],
                  },
                },
              ],
            };
            var sysFind = that.$utils.find(
              that.eipSystemFiled,
              (f) => f.key == element.key
            );
            if (sysFind) {
              //判断是否为系统字段
              switch (element.key) {
                case "CreateTime":
                case "UpdateTime":
                  column.filters = [
                    {
                      data: {
                        type: "datetime",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  that.grid.columns.push(column);
                  break;
                case "RowId":
                  column.filters = [
                    {
                      data: {
                        type: "input",
                        key: null,
                        op: "cn",
                        write: null,
                        options: [],
                      },
                    },
                  ];
                  that.grid.columns.push(column);
                  break;
                case "CreateUser":
                case "UpdateUser":
                  column.filters = [
                    {
                      data: {
                        type: "user",
                        op: "cn",
                        write: null,
                      },
                    },
                  ];
                  column.slots.default = "default";
                  that.grid.columns.push(column);
                  break;
              }
            } else {
              switch (element.type) {
                case that.eipZeroCodeControl.radio:
                case that.eipZeroCodeControl.checkbox:
                case that.eipZeroCodeControl.select:
                  let options = [];
                  element.options.options.forEach((item) => {
                    options.push({
                      value: item.value,
                      label: item.label,
                      checked: false,
                      color: element.options.optionsColor ? item.color : null,
                    });
                  });
                  column.filters = [
                    {
                      data: {
                        type: "select",
                        key: null,
                        op: "jcn",
                        write: null,
                        options: options,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.number:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.switch:
                  column.filters = [
                    {
                      data: {
                        type: "switch",
                        key: null,
                        op: "cn",
                        write: null,
                        options: [
                          {
                            value: 1,
                            label: "是",
                            checked: false,
                            color: "red",
                          },
                          {
                            value: 0,
                            label: "否",
                            checked: false,
                            color: "#1890ff",
                          },
                        ],
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.rate:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.slider:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.uploadFile:
                case that.eipZeroCodeControl.uploadImg:
                  break;
                case that.eipZeroCodeControl.editor:
                  column.type = "html";
                  break;
                case that.eipZeroCodeControl.date:
                  column.filters = [
                    {
                      data: {
                        type: "datetime",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
              }
              if (element.type != that.eipZeroCodeControl.editor) {
                column.slots.default = "default";
              }
              that.grid.columns.push(column);
            }
          });
        setTimeout(function () {
          that.grid.loading = false;
        }, 100);
      });
    },

    /**
     *
     */
    cellStyle({ row }) {
      let option = this.record.options;
    },

    /**
     * 新增
     */
    add() {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      for (let index = 0; index < showColumns.length; index++) {
        const item = showColumns[index];
        data[item.key] = item.options.defaultValue;
      }
      this.grid.data.push({
        ...data,
        RowId: newGuid(),
      });
      //数据源获取
      this.handleInput();
    },
    /**
     * 移除
     * @param {*} item
     */
    remove(item) {
      const index = this.grid.data.indexOf(item);
      if (index !== -1) {
        this.grid.data.splice(index, 1);
      }
      //数据源获取
      this.handleInput();
    },

    /**
     * 删除
     */
    delAll() {
      let that = this;
      let nowChosen = this.$refs[this.record.key].getCheckboxRecords(true);
      //获取其他页显示项
      let otherChosen =
        this.$refs[this.record.key].getCheckboxReserveRecords(true);
      var data = nowChosen.concat(otherChosen);
      //判断是否选择了数据
      if (data.length == 0) {
        this.$message.error("请选择数据");
        return;
      }
      data.forEach((item) => {
        that.remove(item);
      });
    },

    /**
     * 复制数据
     * @param {*} record
     */
    copy(record) {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      showColumns.forEach((item) => {
        data[item.key] = record[item.key];
      });
      const index = this.grid.data.indexOf(record);
      data.RowId = newGuid();
      this.grid.data.splice(index + 1, 0, data);
      this.handleInput();
    },

    /**
     * 初始化数据
     */
    initGridData() {
      let that = this;
      if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.edit) {
        findCorrelationRows({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
          that.handleInput();
        });
      } else if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.add) {
        //获取默认值
        findCorrelationDefault({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
        });
      }
    },
  },
};
</script>
<style lang="less" scoped></style>
